package com.wzy.mall.web.servlet.admin;

import com.alibaba.druid.util.StringUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wzy.mall.model.bo.adminBO.*;
import com.wzy.mall.model.pojo.adminPOJO.GoodsPOJO;
import com.wzy.mall.model.pojo.adminPOJO.TypePOJO;
import com.wzy.mall.model.vo.ResultVO;
import com.wzy.mall.model.vo.adminVO.*;
import com.wzy.mall.service.admin.GoodsService;
import com.wzy.mall.service.admin.impl.GoodsServiceImpl;
import com.wzy.mall.utils.HTTPUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

public class Goods {

    private static ObjectMapper jsonMapper = new ObjectMapper();

    private static GoodsService goodsService = new GoodsServiceImpl();

    /**
     *  获取商品类目
     * @param request
     * @param response
     */
    public static void getType(HttpServletRequest request, HttpServletResponse response) {
        // 没有请求数据，直接调用Service层获取数据库的数据
        List<TypePOJO> typePOJOList = goodsService.getType();

        // 将POJO集合对象封装成VO对象
        ArrayList<TypeVO> typeVOList = new ArrayList<TypeVO>();
        for (TypePOJO typePOJO : typePOJOList) {
            TypeVO typeVO = new TypeVO();
            typeVO.setId(typePOJO.getId());
            typeVO.setName(typePOJO.getTypename());

            typeVOList.add(typeVO);
        }

        ResultVO resultVO = new ResultVO(0, typeVOList, null);

        try {
            response.getWriter().write(jsonMapper.writeValueAsString(resultVO));
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     *  根据typeID获取商品
     * @param request
     * @param response
     */
    public static void getGoodsByType(HttpServletRequest request, HttpServletResponse response) {
        // 获取参数值
        String typeId = request.getParameter("typeId");

        // 调用Service层
        List<GoodsPOJO> goodsPOJOList = goodsService.getGoodsByType(Integer.parseInt(typeId));

        // 将POJO集合对象封装成VO集合对象
        ArrayList<GoodsShowVO> goodsShowVOList = new ArrayList<GoodsShowVO>();
        for (GoodsPOJO goodsPOJO : goodsPOJOList) {
            GoodsShowVO goodsShowVO = new GoodsShowVO();
            goodsShowVO.setId(goodsPOJO.getId());
            goodsShowVO.setImg(goodsPOJO.getImg());
            goodsShowVO.setName(goodsPOJO.getGoodsname());
            goodsShowVO.setPrice(goodsPOJO.getPrice());
            goodsShowVO.setTypeId(goodsPOJO.getId());
            goodsShowVO.setStockNum(goodsPOJO.getStocknum());

            goodsShowVOList.add(goodsShowVO);
        }

        ResultVO resultVO = new ResultVO(0, goodsShowVOList, null);
        try {
            response.getWriter().write(jsonMapper.writeValueAsString(resultVO));
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     *  添加类目
     * @param request
     * @param response
     */
    public static void addType(HttpServletRequest request, HttpServletResponse response) {
        // 参数是JSON数据
        try {
            String requestBody = HTTPUtils.getJSONRequest(request);

            // 将JSON字符串转换为BO对象
            TypeBO typeBO = jsonMapper.readValue(requestBody, TypeBO.class);
            //System.out.println(typeBO);
            String typeName = typeBO.getName();

            // 判空
            if("".equals(typeName)) {
                ResultVO resultVO = new ResultVO(10000, null, "类目名称不能为空哦~");
                response.getWriter().write(jsonMapper.writeValueAsString(resultVO));
                return;
            }

            // 调用Service层将类目添加到数据库
            int result = goodsService.addType(typeName);
            if(result == 0) {
                ResultVO resultVO = new ResultVO(10000, null, "服务器繁忙，请稍后再试~");
                response.getWriter().write(jsonMapper.writeValueAsString(resultVO));
            } else {
                ResultVO resultVO = new ResultVO(0, null, null);
                response.getWriter().write(jsonMapper.writeValueAsString(resultVO));
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     *  删除类目
     * @param request
     * @param response
     */
    public static void deleteType(HttpServletRequest request, HttpServletResponse response) {
        // 获取参数键值对
        String typeId = request.getParameter("typeId");

        // 调用Service层
        int result = goodsService.deleteType(Integer.parseInt(typeId));

        try {
            if(result == 0) {
                ResultVO resultVO = new ResultVO(10000, null, "服务器繁忙，请稍后再试~");
                response.getWriter().write(jsonMapper.writeValueAsString(resultVO));
            } else {
                ResultVO resultVO = new ResultVO(0, null, null);
                response.getWriter().write(jsonMapper.writeValueAsString(resultVO));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     *  图片上传
     * @param request
     * @param response
     */
    public static void imgUpload(HttpServletRequest request, HttpServletResponse response) {
        // 创建工厂类
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // 创建文件上传处理器
        ServletFileUpload upload = new ServletFileUpload(factory);
        try {
            // 使用文件上传处理器获取参数集合
            List<FileItem> items = upload.parseRequest(request);

            Iterator<FileItem> iterator = items.iterator();
            String relativePath = null;
            while(iterator.hasNext()) {
                FileItem item = iterator.next();

                if(!item.isFormField()) {
                    relativePath = processUploadFile(item, request);
                }
            }

            ResultVO resultVO = new ResultVO(0, relativePath, null);
            response.getWriter().write(jsonMapper.writeValueAsString(resultVO));

        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    /**
     *  图片保存到服务器
     * @param item
     * @param request
     * @return
     */
    private static String processUploadFile(FileItem item, HttpServletRequest request) {
        // 获取参数名
        String fieldName = item.getFieldName();
        // 获取文件名
        String fileName = item.getName();
        // 获取文件类型 MIME
        String contentType = item.getContentType();
        // 获取文件的大小（字节）
        long sizeInBytes = item.getSize();

        // 为了解决文件重名问题，在文件名前加上随机生成的UUID
        UUID uuid = UUID.randomUUID();
        fileName = uuid + "-" + fileName;

        // 为了将文件的保存目录下文件数量分布均匀
        // 使用散列，得到文件名的hash值
        int hashCode = fileName.hashCode();
        // 得到hash值的16进制
        String hexString = Integer.toHexString(hashCode);
        // 根据16进制的8个值创建目录，将文件保存在第八个目录里
        char[] chars = hexString.toCharArray();
        // 基础目录images
        StringBuilder basePath = new StringBuilder("static/image");
        for (char aChar : chars) {
            basePath.append("/").append(aChar);
        }
        // 获取文件的相对路径 不是本地路径！
        String relativePath = basePath.toString() + "/" + fileName;
        //System.out.println("相对路径" + relativePath);
        // 获取文件的绝对路径 -- 即本地路径！
        String absolutePath = request.getServletContext().getRealPath(relativePath);
        //System.out.println("绝对路径" + absolutePath);
        // 创建文件对象 -- 需要本地路径
        File file = new File(absolutePath);
        if(!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        try {
            // 将文件写出到指定路径
            // 该写出操作是一个异步方法
            item.write(file);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return relativePath.replace("static/image/", "");
    }

    /**
     *  根据商品ID获取商品数据信息
     * @param request
     * @param response
     */
    public static void getGoodsInfo(HttpServletRequest request, HttpServletResponse response) {
        // 键值对参数
        String id = request.getParameter("id");

        // 调用Service层
        GoodsInfoVO goodsInfoVO = goodsService.getGoodsInfo(id);

        ResultVO resultVO = new ResultVO(0, goodsInfoVO, null);
        try {
            response.getWriter().write(jsonMapper.writeValueAsString(resultVO));
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     *  根据ID删除指定商品的规格
     * @param request
     * @param response
     */
    public static void deleteSpec(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 获取JSON
            String requestBody = HTTPUtils.getJSONRequest(request);

            // 将JSON转换为BO对象
            SpecDeleteBO specDeleteBO = jsonMapper.readValue(requestBody, SpecDeleteBO.class);
            //System.out.println(specDeleteBO);

            // 调用Sercice层
            int result = goodsService.deleteSpec(specDeleteBO);

            if(result == 0) {
                ResultVO resultVO = new ResultVO(10000, null, "服务器繁忙，请稍后再试！");
                response.getWriter().write(jsonMapper.writeValueAsString(resultVO));
            } else {
                ResultVO resultVO = new ResultVO(0, null, null);
                response.getWriter().write(jsonMapper.writeValueAsString(resultVO));
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     *  根据商品ID添加规格
     * @param request
     * @param response
     */
    public static void addSpec(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 获取JSON
            String requestBody = HTTPUtils.getJSONRequest(request);
            // 将JSON封装成BO对象
            SpecAddBO specAddBO = jsonMapper.readValue(requestBody, SpecAddBO.class);

            // 判空
            if(StringUtils.isEmpty(specAddBO.getSpecName())) {
                ResultVO resultVO = new ResultVO(10000, null, "规格名称不能为空哦！");
                response.getWriter().write(jsonMapper.writeValueAsString(resultVO));
                return;
            } else if(specAddBO.getStockNum() == null || specAddBO.getUnitPrice() == null) {
                ResultVO resultVO = new ResultVO(10000, null, "库存量或单价要好好输入啊！魂淡");
                response.getWriter().write(jsonMapper.writeValueAsString(resultVO));
                return;
            }

            // 不调用Service 直接将返回VO对象
            SpecAddVO specAddVO = new SpecAddVO();
            specAddVO.setGoodsId(specAddBO.getGoodsId());
            specAddVO.setSpecName(specAddBO.getSpecName());
            specAddVO.setStockNum(specAddBO.getStockNum());
            specAddVO.setUnitPrice(specAddBO.getUnitPrice());

            ResultVO resultVO = new ResultVO(0, specAddVO, null);
            response.getWriter().write(jsonMapper.writeValueAsString(resultVO));

            //// 调用Service层
            //int result = goodsService.addSpec(specAddBO);
            //
            //if(result == 404) {
            //    ResultVO resultVO = new ResultVO(10000, null, "添加失败啦!");
            //    response.getWriter().write(jsonMapper.writeValueAsString(resultVO));
            //
            //} else if(result == 505) {
            //    ResultVO resultVO = new ResultVO(10000, null, "规格名称重复啦!(～￣(OO)￣)ブ");
            //    response.getWriter().write(jsonMapper.writeValueAsString(resultVO));
            //
            //} else if(result == 200) {
            //    SpecAddVO specAddVO = new SpecAddVO();
            //    specAddVO.setGoodsId(specAddBO.getGoodsId());
            //    specAddVO.setSpecName(specAddBO.getSpecName());
            //    specAddVO.setStockNum(specAddBO.getStockNum());
            //    specAddVO.setUnitPrice(specAddBO.getUnitPrice());
            //
            //    ResultVO resultVO = new ResultVO(0, specAddVO, null);
            //    response.getWriter().write(jsonMapper.writeValueAsString(resultVO));
            //}

        } catch (IOException e) {
            e.printStackTrace();
            ResultVO resultVO = new ResultVO(10000, null, "出问题啦！你的库存量或单价真的是数字吗！？");
            try {
                response.getWriter().write(jsonMapper.writeValueAsString(resultVO));
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }

    /**
     *  根据ID删除商品
     * @param request
     * @param response
     */
    public static void deleteGoods(HttpServletRequest request, HttpServletResponse response) {
        // 获取键值对参数
        String id = request.getParameter("id");

        // 调用Service层
        int result = goodsService.deleteGoodsByID(Integer.parseInt(id));

        try {
            if(result == 0) {
                ResultVO resultVO = new ResultVO(10000, null, "服务器繁忙，请稍后再试！");
                response.getWriter().write(jsonMapper.writeValueAsString(resultVO));
            } else {
                ResultVO resultVO = new ResultVO(0, null, null);
                response.getWriter().write(jsonMapper.writeValueAsString(resultVO));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     *  更改商品数据
     * @param request
     * @param response
     */
    public static void updateGoods(HttpServletRequest request, HttpServletResponse response) {
        // 获取JSON数据
        try {
            String requestBody = HTTPUtils.getJSONRequest(request);

            GoodsUpdateBO goodsUpdateBO = jsonMapper.readValue(requestBody, GoodsUpdateBO.class);
            //System.out.println(goodsUpdateBO);

            // 判断规格名是否为空
            List<SpecUpdateBO> specUpdateBOList = goodsUpdateBO.getSpecList();
            ArrayList<String> specNameList = new ArrayList<String>();
            for (SpecUpdateBO specUpdateBO : specUpdateBOList) {
                String specName = specUpdateBO.getSpecName();
                if(StringUtils.isEmpty(specName)) {
                    ResultVO resultVO = new ResultVO(10000, null, "规格名称不能为空啊 魂淡！！！");
                    response.getWriter().write(jsonMapper.writeValueAsString(resultVO));
                    return;
                }
                if(!specNameList.contains(specName)) {
                    specNameList.add(specName);
                } else {
                    ResultVO resultVO = new ResultVO(10000, null, "规格名称重复啦！！");
                    response.getWriter().write(jsonMapper.writeValueAsString(resultVO));
                    return;
                }
            }

            // 调用Service层
            int result = goodsService.updateGoodsByID(goodsUpdateBO);
            if(result == 0) {
                ResultVO resultVO = new ResultVO(10000, null, "服务器繁忙，请稍后再试！！！");
                response.getWriter().write(jsonMapper.writeValueAsString(resultVO));
            } else {
                ResultVO resultVO = new ResultVO(0, null, null);
                response.getWriter().write(jsonMapper.writeValueAsString(resultVO));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     *  添加商品
     * @param request
     * @param response
     */
    public static void addGoods(HttpServletRequest request, HttpServletResponse response) {

        try {
            String requestBody = HTTPUtils.getJSONRequest(request);
            // 封装BO对象
            GoodsAddBO goodsAddBO = jsonMapper.readValue(requestBody, GoodsAddBO.class);

            // 判空
            // 商品名和图片
            if(StringUtils.isEmpty(goodsAddBO.getName())) {
                ResultVO resultVO = new ResultVO(10000, null, "商品名怎么可以不输入啊 魂淡");
                response.getWriter().write(jsonMapper.writeValueAsString(resultVO));
                return;
            } else if(StringUtils.isEmpty(goodsAddBO.getImg())) {
                ResultVO resultVO = new ResultVO(10000, null, "给张图片啊 笨蛋！");
                response.getWriter().write(jsonMapper.writeValueAsString(resultVO));
                return;
            }

            // 规格名、单价、库存量
            ArrayList<String> specNameList = new ArrayList<String>();
            for (SpecAddBO spec : goodsAddBO.getSpecList()) {
                if(StringUtils.isEmpty(spec.getSpecName())) {
                    ResultVO resultVO = new ResultVO(10000, null, "规格名称呢！？");
                    response.getWriter().write(jsonMapper.writeValueAsString(resultVO));
                    return;
                } else if(spec.getUnitPrice() == null) {
                    ResultVO resultVO = new ResultVO(10000, null, "单价呢！？");
                    response.getWriter().write(jsonMapper.writeValueAsString(resultVO));
                    return;
                } else if(spec.getStockNum() == null) {
                    ResultVO resultVO = new ResultVO(10000, null, "库存量呢！？");
                    response.getWriter().write(jsonMapper.writeValueAsString(resultVO));
                    return;
                }
                // 将规格名称放入集合
                String specName = spec.getSpecName();
                if(!specNameList.contains(specName)) {
                    specNameList.add(specName);
                } else {
                    ResultVO resultVO = new ResultVO(10000, null, "规格名称重复啦！！");
                    response.getWriter().write(jsonMapper.writeValueAsString(resultVO));
                    return;
                }
            }

            int result = goodsService.addGoods(goodsAddBO);
            if(result == 0) {
                ResultVO resultVO = new ResultVO(10000, null, "服务器繁忙，请稍后再试！！");
                response.getWriter().write(jsonMapper.writeValueAsString(resultVO));
            } else if(result == 505) {
                ResultVO resultVO = new ResultVO(10000, null, "该类目下存在同名商品啦！！！");
                response.getWriter().write(jsonMapper.writeValueAsString(resultVO));
            } else {
                ResultVO resultVO = new ResultVO(0, null, null);
                response.getWriter().write(jsonMapper.writeValueAsString(resultVO));
            }

        } catch (IOException e) {
            try {
                ResultVO resultVO = new ResultVO(10000, null, "出问题啦！你的库存量或单价真的是数字吗！？");
                response.getWriter().write(jsonMapper.writeValueAsString(resultVO));
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }


    }

    /**
     *  获取未回复留言
     * @param request
     * @param response
     */
    public static void noReplyMsg(HttpServletRequest request, HttpServletResponse response) {
        // 没有请求参数 直接调用Service层
        List<ReplyNVO> replyNVOList = goodsService.noReplyMsg();

        try {
            if(replyNVOList == null) {
                ResultVO resultVO = new ResultVO(10000, null, "服务器繁忙啊啊啊！！");
                response.getWriter().write(jsonMapper.writeValueAsString(resultVO));
            } else {
                ResultVO resultVO = new ResultVO(0, replyNVOList, null);
                response.getWriter().write(jsonMapper.writeValueAsString(resultVO));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     *  获取已回复的留言
     * @param request
     * @param response
     */
    public static void repliedMsg(HttpServletRequest request, HttpServletResponse response) {
        // 没有请求参数 直接调用Service层
        List<RepliedYVO> repliedYVOList = goodsService.repliedMsg();

        try {
            if(repliedYVOList == null) {
                ResultVO resultVO = new ResultVO(10000, null, "服务器繁忙啊啊啊！！");
                response.getWriter().write(jsonMapper.writeValueAsString(resultVO));
            } else {
                ResultVO resultVO = new ResultVO(0, repliedYVOList, null);
                response.getWriter().write(jsonMapper.writeValueAsString(resultVO));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     *  回复留言
     * @param request
     * @param response
     */
    public static void reply(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 获取JSON数据
            String requestBody = HTTPUtils.getJSONRequest(request);
            // 转换为BO对象
            ReplyBO replyBO = jsonMapper.readValue(requestBody, ReplyBO.class);

            // Service层 实际上是更新数据库
            int result = goodsService.reply(replyBO);
            if(result == 0) {
                ResultVO resultVO = new ResultVO(10000, null, "服务器繁忙啊啊啊！！");
                response.getWriter().write(jsonMapper.writeValueAsString(resultVO));
            } else {
                ResultVO resultVO = new ResultVO(0, null, null);
                response.getWriter().write(jsonMapper.writeValueAsString(resultVO));
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
